<template>
  <div class="notices-page">
    <div class="page-header">
      <h1 class="page-title">学习通知</h1>
      <p class="page-desc">关注班级公告、作业发布与考试安排，提前做好准备</p>
    </div>

    <el-card class="filter-card" shadow="hover">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="学期">
          <el-select 
            v-model="filterForm.semester" 
            placeholder="选择学期" 
            style="width: 150px"
            @change="applyFilter"
          >
            <el-option label="全部" value="" />
            <el-option label="2025秋季" value="2025秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2024春季" value="2024春季" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知类型">
          <el-select 
            v-model="filterForm.noticeType" 
            placeholder="全部" 
            style="width: 150px"
            @change="applyFilter"
          >
            <el-option label="全部" value="" />
            <el-option label="系统通知" value="system" />
            <el-option label="课程通知" value="course" />
            <el-option label="考试通知" value="exam" />
            <el-option label="作业通知" value="homework" />
            <el-option label="一般通知" value="general" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="filterForm.readStatus" 
            placeholder="全部" 
            style="width: 150px"
            @change="applyFilter"
          >
            <el-option label="全部" value="" />
            <el-option label="未读" value="unread" />
            <el-option label="已读" value="read" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadNotices">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button @click="markAllRead" v-if="unreadCount > 0">
            全部标记已读
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 未读数量提示 -->
      <div v-if="unreadCount > 0" class="unread-tip">
        <el-icon><Bell /></el-icon>
        您有 <strong>{{ unreadCount }}</strong> 条未读通知
      </div>
    </el-card>

    <el-card class="data-card" shadow="hover" v-loading="loading">
      <div v-if="filteredNotices.length === 0" class="empty-state">
        <el-empty description="暂无学习通知" />
      </div>
      <div v-else class="notices-list">
        <div 
          v-for="notice in filteredNotices" 
          :key="notice.noticeId"
          class="notice-item"
          :class="{ 
            'notice-unread': !notice.read,
            'notice-urgent': notice.priority === 2
          }"
          @click="handleNoticeClick(notice)"
        >
          <div class="notice-header">
            <div class="notice-title-row">
              <h3 class="notice-title">
                <el-badge v-if="!notice.read" is-dot type="danger">
                  {{ notice.title }}
                </el-badge>
                <span v-else>{{ notice.title }}</span>
              </h3>
              <div class="notice-tags">
                <el-tag :type="getNoticeTypeColor(notice.noticeType)" size="small">
                  {{ getNoticeTypeText(notice.noticeType) }}
                </el-tag>
                <el-tag v-if="notice.priority > 0" :type="getPriorityColor(notice.priority)" size="small">
                  {{ getPriorityText(notice.priority) }}
                </el-tag>
              </div>
            </div>
            <span class="notice-time">{{ formatTime(notice.publishTime) }}</span>
          </div>
          <p class="notice-content">{{ notice.content }}</p>
          <div class="notice-footer">
            <div class="footer-left">
              <el-tag v-if="!notice.read" size="small" type="danger">未读</el-tag>
              <el-tag v-else size="small" type="info">已读</el-tag>
              <span class="publisher-info">
                <el-icon><User /></el-icon>
                {{ notice.publisherName }} ({{ getPublisherTypeText(notice.publisherType) }})
              </span>
              <span v-if="notice.semester" class="semester-info">
                <el-icon><Calendar /></el-icon>
                {{ notice.semester }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 通知详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentNotice.title"
      width="700px"
      @close="handleDialogClose"
    >
      <div class="notice-detail">
        <div class="detail-tags">
          <el-tag :type="getNoticeTypeColor(currentNotice.noticeType)" size="small">
            {{ getNoticeTypeText(currentNotice.noticeType) }}
          </el-tag>
          <el-tag v-if="currentNotice.priority > 0" :type="getPriorityColor(currentNotice.priority)" size="small">
            {{ getPriorityText(currentNotice.priority) }}
          </el-tag>
          <el-tag v-if="currentNotice.read" type="info" size="small">已读</el-tag>
          <el-tag v-else type="danger" size="small">未读</el-tag>
        </div>
        
        <div class="detail-meta">
          <div class="meta-item">
            <el-icon><User /></el-icon>
            <strong>发布者：</strong>
            {{ currentNotice.publisherName }} ({{ getPublisherTypeText(currentNotice.publisherType) }})
          </div>
          <div class="meta-item" v-if="currentNotice.semester">
            <el-icon><Calendar /></el-icon>
            <strong>学期：</strong>
            {{ currentNotice.semester }}
          </div>
          <div class="meta-item">
            <el-icon><Clock /></el-icon>
            <strong>发布时间：</strong>
            {{ formatTime(currentNotice.publishTime) }}
          </div>
          <div class="meta-item" v-if="currentNotice.read && currentNotice.readTime">
            <el-icon><Check /></el-icon>
            <strong>阅读时间：</strong>
            {{ formatTime(currentNotice.readTime) }}
          </div>
        </div>
        
        <div class="detail-content">
          <strong>通知内容：</strong>
          <p>{{ currentNotice.content }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Clock, User, Calendar, Check, Bell } from '@element-plus/icons-vue'
import { getStudentNotices, markNoticeRead } from '../api/studentUser'

const loading = ref(false)
const notices = ref([])

// 使用 reactive 定义表单数据
const filterForm = reactive({
  semester: '',
  noticeType: '',
  readStatus: ''
})

// 未读数量
const unreadCount = computed(() => {
  return notices.value.filter(n => !n.read).length
})

// 过滤后的通知列表
const filteredNotices = computed(() => {
  let result = notices.value

  // 按通知类型过滤
  if (filterForm.noticeType) {
    result = result.filter(n => n.noticeType === filterForm.noticeType)
  }

  // 按学期过滤
  if (filterForm.semester) {
    result = result.filter(n => n.semester === filterForm.semester)
  }

  // 按阅读状态过滤
  if (filterForm.readStatus === 'read') {
    result = result.filter(n => n.read)
  } else if (filterForm.readStatus === 'unread') {
    result = result.filter(n => !n.read)
  }

  return result
})

const dialogVisible = ref(false)
const currentNotice = ref({})

const user = JSON.parse(localStorage.getItem('user') || '{}')

const loadNotices = async () => {
  loading.value = true
  try {
    // 兼容多种可能的字段名：studentId, stuId, stuNo
    const studentId = user.studentId || user.stuId || user.stuNo
    if (!studentId) {
      ElMessage.error('无法获取学生信息，请重新登录')
      loading.value = false
      return
    }
    const response = await getStudentNotices(studentId, null)
    if (response.code === 200) {
      notices.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取学习通知失败')
    }
  } catch (error) {
    console.error('获取学习通知失败:', error)
    ElMessage.error('获取学习通知失败')
  } finally {
    loading.value = false
  }
}

const applyFilter = () => {
  // 过滤逻辑已在 computed 中处理
}

const handleNoticeClick = async (notice) => {
  currentNotice.value = notice
  dialogVisible.value = true
  
  // 如果是未读通知，标记为已读
  if (!notice.read) {
    try {
      const studentId = user.studentId || user.stuId || user.stuNo
      const response = await markNoticeRead(studentId, notice.noticeId)
      if (response.code === 200) {
        notice.read = true
        notice.readTime = new Date()
      }
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
}

// 全部标记已读
const markAllRead = () => {
  ElMessageBox.confirm('确定将所有未读通知标记为已读吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      const studentId = user.studentId || user.stuId || user.stuNo
      const unreadNotices = notices.value.filter(n => !n.read)
      
      for (const notice of unreadNotices) {
        await markNoticeRead(studentId, notice.noticeId)
        notice.read = true
        notice.readTime = new Date()
      }
      
      ElMessage.success('已全部标记为已读')
    } catch (error) {
      console.error('标记失败:', error)
      ElMessage.error('标记失败')
    }
  }).catch(() => {})
}

const handleDialogClose = () => {
  currentNotice.value = {}
}

// 辅助方法
const getNoticeTypeText = (type) => {
  const map = {
    'system': '系统通知',
    'course': '课程通知',
    'exam': '考试通知',
    'homework': '作业通知',
    'general': '一般通知'
  }
  return map[type] || type
}

const getNoticeTypeColor = (type) => {
  const map = {
    'system': 'danger',
    'course': 'primary',
    'exam': 'warning',
    'homework': 'success',
    'general': 'info'
  }
  return map[type] || ''
}

const getPriorityText = (priority) => {
  const map = {
    0: '普通',
    1: '重要',
    2: '紧急'
  }
  return map[priority] || priority
}

const getPriorityColor = (priority) => {
  const map = {
    0: 'info',
    1: 'warning',
    2: 'danger'
  }
  return map[priority] || ''
}

const getPublisherTypeText = (type) => {
  const map = {
    'admin': '管理员',
    'teacher': '教师'
  }
  return map[type] || type
}

const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

onMounted(() => {
  loadNotices()
})
</script>

<style scoped>
.notices-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.page-desc {
  font-size: 14px;
  color: #6c757d;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.data-card {
  border-radius: 12px;
  min-height: 400px;
}

.empty-state {
  padding: 60px 0;
}

.notices-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.notice-item {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
}

.notice-item:hover {
  background: #e9ecef;
  transform: translateX(4px);
}

.notice-item.notice-unread {
  background: #fff7e6;
  border-left-color: #ff9800;
}

.notice-item.notice-unread:hover {
  background: #fff3cd;
}

.notice-item.notice-urgent {
  border-left-color: #dc3545;
  background: #fff0f0;
}

.notice-item.notice-urgent:hover {
  background: #ffe6e6;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.notice-title-row {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.notice-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.notice-tags {
  display: flex;
  gap: 6px;
}

.notice-time {
  font-size: 12px;
  color: #6c757d;
  white-space: nowrap;
  margin-left: 12px;
}

.notice-content {
  font-size: 14px;
  color: #495057;
  line-height: 1.6;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.notice-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.publisher-info,
.semester-info {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #6c757d;
}

.unread-tip {
  margin-top: 12px;
  padding: 12px;
  background: #fff7e6;
  border-left: 4px solid #ff9800;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #856404;
}

.unread-tip strong {
  color: #ff9800;
}

.notice-detail {
  padding: 12px 0;
}

.detail-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.detail-meta {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #495057;
  margin-bottom: 8px;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.meta-item strong {
  margin-left: 4px;
}

.detail-content {
  font-size: 15px;
  color: #2c3e50;
  line-height: 1.8;
  white-space: pre-wrap;
}

.el-form--inline .el-form-item {
  margin-right: 16px;
}
</style>


